package com.eningqu.aipen.ui.adapter;/**
 * Package:com.eningqu.aipen.ui.adapter
 * Author:starr
 * Time:2023/11/7 19:34
 * Description: 文心一言对话列表适配器
 */

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.eningqu.aipen.demo.R;
import com.eningqu.aipen.logic.model.chat.ChatBodyBean;

import java.util.List;

/**
 * Package:com.eningqu.aipen.ui.adapter
 * Author:starr
 * Time:2023/11/7 19:34
 * Description:
 */
public class MsgAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private List<ChatBodyBean.MessagesDTO> list;

    public MsgAdapter(List<ChatBodyBean.MessagesDTO> list) {
        this.list = list;
    }

    public static class LeftViewHolder extends RecyclerView.ViewHolder {
        TextView leftMsg;

        public LeftViewHolder(@NonNull View itemView) {
            super(itemView);
            leftMsg = itemView.findViewById(R.id.tv_msg_left);
        }
    }

    public static class RightViewHolder extends RecyclerView.ViewHolder {
        TextView rightMsg;

        public RightViewHolder(@NonNull View itemView) {
            super(itemView);
            rightMsg = itemView.findViewById(R.id.tv_msg_right);
        }
    }

    @Override
    public int getItemViewType(int position) {
        ChatBodyBean.MessagesDTO msg = list.get(position);
        if (TextUtils.equals(msg.role, "user")) {
            return 0;//user-right
        } else {
            return 1;//assistant-left
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        if (viewType == 1) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_msg_left, viewGroup, false);
            return new LeftViewHolder(view);
        } else {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_msg_right, viewGroup, false);
            return new RightViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        ChatBodyBean.MessagesDTO msg = list.get(position);
        if (holder instanceof LeftViewHolder) {
            ((LeftViewHolder) holder).leftMsg.setText(msg.content);
        } else if (holder instanceof RightViewHolder) {
            ((RightViewHolder) holder).rightMsg.setText(msg.content);
        } else {
            throw new IllegalArgumentException("类型异常");
        }
    }

    @Override
    public int getItemCount() {
        return list.size();
    }
}
